<?php
/**
 * Created by PhpStorm.
 * User: man0sions
 * Date: 16/7/26
 * Time: 上午11:06
 */

namespace LuciferP\Controller;

use LuciferP\Http\Request;
use LuciferP\Http\Response;


/**
 * Class Controller
 * @package app\components\Iabstract
 * @author Luficer.p <81434146@qq.com>
 */
abstract class Controller{
    /**
     * @var
     */
    protected $id;
    /**
     * @var
     */
    protected $action;
    /**
     * @var
     */
    protected $base_dir=BASE_PATH;
    /**
     * @var string
     */
    protected $view_path;
    /**
     * @var string
     */
    protected $layout='/layouts/main.php';

    protected $layout_path;

    protected $response;

    protected $request;

    function __construct($id,$action,Request $request,Response $response)
    {
        $this->id = $id;
        $this->action = $action;
        $this->response = $response;
        $this->request = $request;
    }

    /**
     * @param array $data
     * @return string
     */
    private function renderInternal($data=[]){
        extract($data);
        ob_start();
        require $this->view_path;

        $content = ob_get_contents();
        ob_end_clean();
        return $content;
    }

    /**
     * @param array $data
     * @return string
     * @throws \Exception
     */
    public function render($data=[]){

        $this->view_path  = $this->base_dir."/views/".strtolower($this->id)."/{$this->action}.php";
        if(!file_exists($this->view_path))
        {
            throw new \Exception("view file not exists: {$this->view_path}");
        }

        $this->layout_path = $this->base_dir."/views/".$this->layout;

        if(!file_exists($this->layout_path))
        {
            throw new \Exception("layout file not exists: {$this->layout_path}");
        }


        ob_start();
        $content = $this->renderInternal($data);
        require $this->layout_path;
        $html = ob_get_contents();
        ob_end_clean();

        return $html;
    }

    /**
     * @param $path
     * @param array $params
     * @return string
     */
    public function createUrl($path,$params=[]){
        $values = [];
        foreach($params as $name=>$param)
        {
            $values[]=urlencode($name).'/'.urlencode($param);
        }
        return $this->request['homeUrl'].$path.join("/",$values);
    }

    /**
     * @param $url
     */
    public function redirect($url){
        header("location:$url");
        exit();
    }



}